package pers.zw.dao.impl;

import org.dom4j.Document;
import org.dom4j.Element;
import pers.zw.dao.IUserDao;
import pers.zw.domain.User;
import pers.zw.util.XMLUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class UserDaoImpl implements IUserDao {

    private User findUser(Element e) {
        User user = new User();
        user.setId(e.attributeValue("id"));
        user.setEmail(e.attributeValue("email"));
        user.setUserName(e.attributeValue("userName"));
        user.setUserPwd(e.attributeValue("userPwd"));
        String birthday = e.attributeValue("birthday");
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException parseException) {
            parseException.printStackTrace();
        }
        return user;
    }

    @Override
    public User find(String userName, String userPwd) {
        try {
            Document document = XMLUtils.getDocument();
            Element e = (Element) document.selectSingleNode("//user[@userName = '" + userName + "' " +
                    "and @userPwd = '" + userPwd + "']");
            if (e == null) return null;

            return findUser(e);
        } catch (Exception e) {
            throw new RuntimeException("no document || invalid birthday");
        }
    }

    @Override
    public User find(String userName) {
        try {
            Document document = XMLUtils.getDocument();
            Element e = (Element) document.selectSingleNode("//user[@userName = '" + userName + "']");
            if (e == null) return null;

            return findUser(e);
        } catch (Exception e) {
            throw new RuntimeException("no document || invalid birthday");
        }
    }

    @Override
    public void add(User user) {
        try {
            Document document = XMLUtils.getDocument();
            Element root = document.getRootElement();
            Element user_node = root.addElement("user");

            user_node.addAttribute("id", user.getId());
            user_node.addAttribute("userName", user.getUserName());
            user_node.addAttribute("userPwd", user.getUserPwd());
            user_node.addAttribute("email", user.getEmail());
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            user_node.addAttribute("birthday", sdf.format(user.getBirthday()));

            XMLUtils.write2Xml(document);
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }
}
